<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libcoap: coap_context(3)</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr id="projectrow">
  <td id="projectalign">
   <div id="projectname">libcoap<span id="projectnumber">&#160;4.2.0</span>
   </div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.8 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search/",'.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
$(function() {
  initMenu('',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */
$(document).ready(function(){initNavTree('man_coap_context.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<div id="MSearchResults">
<div class="SRPage">
<div id="SRIndex">
<div id="SRResults"></div>
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
</div>
</div>
</div>
</div>

<div><div class="header">
  <div class="headertitle"><div class="title">coap_context(3)</div></div>
</div><!--header-->
<div class="contents">
<div class="textblock"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>coap_context</title><link rel="stylesheet" type="text/css" href="docbook-xsl.css" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /></head><body><div xml:lang="en" class="refentry" lang="en"><a id="id1337"></a><div class="titlepage"></div><div class="refnamediv"><h2>NAME</h2><p>coap_context, coap_new_context, coap_free_context, coap_context_set_pki, coap_context_set_psk, coap_new_endpoint, coap_free_endpoint, coap_endpoint_set_default_mtu, coap_endpoint_str — Work with CoAP contexts</p></div><div class="refsynopsisdiv"><a id="_synopsis"></a><h2>SYNOPSIS</h2><p><span class="strong"><strong>#include &lt;coap2/coap.h&gt;</strong></span></p><p><span class="strong"><strong>coap_context_t *coap_new_context(const coap_address_t *<span class="emphasis"><em>listen_addr</em></span>);</strong></span></p><p><span class="strong"><strong>void coap_free_context(coap_context_t *<span class="emphasis"><em>context</em></span>);</strong></span></p><p><span class="strong"><strong>int coap_context_set_pki(coap_context_t *<span class="emphasis"><em>context</em></span>,
coap_dtls_pki_t *<span class="emphasis"><em>setup_data</em></span>);</strong></span></p><p><span class="strong"><strong>int coap_context_set_pki_root_cas(coap_context_t *<span class="emphasis"><em>context</em></span>,
const char *<span class="emphasis"><em>ca_file</em></span>, const char *<span class="emphasis"><em>ca_dir</em></span>);</strong></span></p><p><span class="strong"><strong>int coap_context_set_psk(coap_context_t *<span class="emphasis"><em>context</em></span>, const char *<span class="emphasis"><em>hint</em></span>,
const uint8_t *<span class="emphasis"><em>key</em></span>, size_t <span class="emphasis"><em>key_len</em></span>);</strong></span></p><p><span class="strong"><strong>coap_endpoint_t *coap_new_endpoint(coap_context_t *<span class="emphasis"><em>context</em></span>,
const coap_address_t *<span class="emphasis"><em>listen_addr</em></span>, coap_proto_t <span class="emphasis"><em>proto</em></span>);</strong></span></p><p><span class="strong"><strong>void coap_free_endpoint(coap_endpoint_t *<span class="emphasis"><em>endpoint</em></span>);</strong></span></p><p><span class="strong"><strong>void coap_endpoint_set_default_mtu(coap_endpoint_t *<span class="emphasis"><em>endpoint</em></span>,
unsigned <span class="emphasis"><em>mtu</em></span>);</strong></span></p><p>Link with <span class="strong"><strong>-lcoap-2</strong></span>, <span class="strong"><strong>-lcoap-2-gnutls</strong></span>,
<span class="strong"><strong>-lcoap-2-openssl</strong></span> or
<span class="strong"><strong>-lcoap-2-tinydtls</strong></span> depending on your (D)TLS library
type.</p></div><div class="refsect1"><a id="_description"></a><h2>DESCRIPTION</h2><p>This man page focuses on the CoAP Context.</p><p>The CoAP stack’s global state is stored in a coap_context_t Context object.
Resources, Endpoints and Sessions are associated with this context object.
There can be more than one coap_context_t object per application, it is up to
the application to manage each one accordingly.</p><p>The Session network traffic can be encrypted or un-encrypted if there is an
underlying TLS library.</p><p>If TLS is going to be used for encrypting the network traffic, then the TLS
information for Pre-Shared Keys (PSK) or Public Key Infrastructure (PKI) needs
to be configured before any network traffic starts to flow. For Servers, this
has to be done before the Endpoint is created, for Clients, this is done
during the Client Session set up.</p><p>For Servers, all the encryption information is held internally by the TLS
Context level and the CoAP Context level as the Server is listening for new
incoming traffic based on the Endpoint definition.  The TLS and CoAP session
will not get built until the new traffic starts, which is done by the libcoap
library, with the session having a reference count of 1.</p><p>For Clients, all the encryption information can be held at the TLS Context and
CoAP Context levels, or at the TLS Session and CoAP Session levels.  If
defined at the Context level, then when Sessions are created, they will
inherit the Context definitions, unless they have separately been defined for
the Session level, in which case the Session version will get used.
Typically the information will be configured at the Session level for Clients.</p><p>In principle the set-up sequence for CoAP Servers looks like</p><pre class="screen">coap_new_context()
coap_context_set_pki_root_cas() - if the root CAs need to be updated and PKI
coap_context_set_pki() and/or coap_context_set_psk() - if encryption is required
coap_new_endpoint()</pre><p>Multiple endpoints can be set up per Context, each listening for a new traffic
flow with different TCP/UDP protocols, TLS protocols, port numbers etc. When a
new traffic flow is started, then the CoAP library will create and start a new
server session.</p><p>In principle the set-up sequence for CoAP Clients looks like</p><pre class="screen">coap_new_context()
coap_context_set_pki_root_cas() if the root CAs need to be updated and PKI
coap_new_client_session(), coap_new_client_session_pki() or coap_new_client_session_psk()</pre><p>Multiple client sessions are supported per Context.</p><p>The <span class="strong"><strong>coap_new_context</strong></span>() function creates a new Context that is then used
to keep all the CoAP Resources, Endpoints and Sessions information.
The optional <span class="emphasis"><em>listen_addr</em></span> parameter, if set for a CoAP server, creates an
Endpoint that is added to the <span class="emphasis"><em>context</em></span> that is listening for un-encrypted
traffic on the IP address and port number defined by <span class="emphasis"><em>listen_addr</em></span>.</p><p>The <span class="strong"><strong>coap_free_context</strong></span>() function must be used to release the CoAP stack
context.  It clears all entries from the receive queue and send queue and
deletes the Resources that have been registered with <span class="emphasis"><em>context</em></span>, and frees the
attached Sessions and Endpoints.</p><p>The <span class="strong"><strong>coap_context_set_pki</strong></span>() function, for a specific <span class="emphasis"><em>context</em></span>, is used to
configure the TLS context using the <span class="emphasis"><em>setup_data</em></span> variables as defined in the
coap_dtls_pki_t structure  - see *coap_encrytion(*3).</p><p>The <span class="strong"><strong>coap_context_set_pki_root_cas</strong></span>() function is used to define a set of
root CAs to be used instead of the default set of root CAs provided as a part
of the TLS library.  <span class="emphasis"><em>ca_file</em></span> points to a PEM encoded file containing the
list of CAs.  <span class="emphasis"><em>ca_file can be NULL.  _ca_dir</em></span> points to a directory
containing a set of PEM encoded files containing rootCAs.  <span class="emphasis"><em>ca_dir</em></span> can be
NULL. One or both of <span class="emphasis"><em>ca_file</em></span> and <span class="emphasis"><em>ca_dir</em></span> must be set.</p><p>The <span class="strong"><strong>coap_context_set_psk</strong></span>() function is used to configure the TLS context
using the server <span class="emphasis"><em>hint</em></span>, PreShared Key <span class="emphasis"><em>key</em></span> with length <span class="emphasis"><em>key_len</em></span>.
All parameters must be defined, NULL is not valid.  An empty string is valid
for <span class="emphasis"><em>hint</em></span>.  <span class="emphasis"><em>key_len</em></span> must be greater than 0.  This function can only be used
for Servers as it provides a <span class="emphasis"><em>hint</em></span>, not an <span class="emphasis"><em>identity</em></span>.</p><p>The <span class="strong"><strong>coap_new_endpoint</strong></span>() function creates a new endpoint for <span class="emphasis"><em>context</em></span> that
is listening for new traffic on the IP address and port number defined by
<span class="emphasis"><em>listen_addr</em></span>.
Different CoAP protocols can be defined for <span class="emphasis"><em>proto</em></span> - the current supported
list is:</p><pre class="programlisting">COAP_PROTO_UDP
COAP_PROTO_DTLS
COAP_PROTO_TCP
COAP_PROTO_TLS</pre><p>The <span class="strong"><strong>coap_free_endpoint</strong></span>() function must be used to free off the <span class="emphasis"><em>endpoint</em></span>.
It clears out all the sessions associated with this endpoint.</p><p>The <span class="strong"><strong>coap_endpoint_set_default_mtu</strong></span>() function is used to set the MTU size
(the maximum message size) of the data in a packet, excluding any IP or
TCP/UDP overhead to <span class="emphasis"><em>mtu</em></span> for the <span class="emphasis"><em>endpoint</em></span>.  A sensible default is 1280.</p></div><div class="refsect1"><a id="_return_values"></a><h2>RETURN VALUES</h2><p><span class="strong"><strong>coap_new_context</strong></span>() function returns a newly created context or
NULL if there is a creation failure.</p><p><span class="strong"><strong>coap_context_set_pki</strong></span>(), <span class="strong"><strong>coap_context_set_pki_root_cas</strong></span>() and
<span class="strong"><strong>coap_context_set_psk</strong></span>() functions return 1 on success, 0 on failure.</p><p><span class="strong"><strong>coap_new_endpoint</strong></span>() function returns a newly created endpoint or
NULL if there is a creation failure.</p></div><div class="refsect1"><a id="_examples"></a><h2>EXAMPLES</h2><p><span class="strong"><strong>CoAP Server Non-Encrypted Setup</strong></span></p><pre class="programlisting">#include &lt;coap2/coap.h&gt;

static coap_context_t *
setup_server_context (void) {
  coap_endpoint_t *endpoint;
  coap_address_t listen_addr;
  coap_context_t *context = coap_new_context(NULL);

  if (!context)
    return NULL;

  coap_address_init(&amp;listen_addr);
  listen_addr.addr.sa.sa_family = AF_INET;
  listen_addr.addr.sin.sin_port = htons (5683);

  endpoint = coap_new_endpoint(context, &amp;listen_addr, COAP_PROTO_UDP);
  if (!endpoint) {
    coap_free_context(context);
    return NULL;
  }

  /* See coap_resource(3) */
  init_resources(context);

  return context;
}</pre><p><span class="strong"><strong>CoAP Server DTLS PKI Setup</strong></span></p><pre class="programlisting">#include &lt;coap2/coap.h&gt;

typedef struct valid_cns_t {
  int count;
  char **cn_list;
} valid_cns_t;

/*
 * Common Name (CN) Callback verifier
 */
static int
verify_cn_callback(const char *cn,
                   const uint8_t *asn1_public_cert,
                   size_t asn1_length,
                   coap_session_t *session,
                   unsigned depth,
                   int validated,
                   void *arg
) {
  valid_cns_t *valid_cn_list = ( valid_cns_t*)arg;
  int i;

  /* Check that the CN is valid */
  for (i = 0; i &lt; valid_cn_list-&gt;count; i++) {
    if (!strcasecmp(cn, valid_cn_list-&gt;cn_list[i])) {
      return 1;
    }
  }
  return 0;
}

typedef struct sni_def_t {
  char* sni;
  coap_dtls_key_t key;
} sni_def_t;

typedef struct valid_snis_t {
  int count;
  sni_def_t *sni_list;
} valid_snis_t;

/*
 * Subject Name Identifier (SNI) callback verifier
 */
static coap_dtls_key_t *
verify_sni_callback(const char *sni,
                    void *arg
) {
  valid_snis_t *valid_sni_list = (valid_snis_t *)arg;
  int i;

  /* Check that the SNI is valid */
  for (i = 0; i &lt; valid_sni_list-&gt;count; i++) {
    if (!strcasecmp(sni, valid_sni_list-&gt;sni_list[i].sni)) {
      return &amp;valid_sni_list-&gt;sni_list[i].key;
    }
  }
  return NULL;
}

/*
 * Set up PKI encryption information
 */
static coap_context_t *
setup_server_context_pki (const char *public_cert_file,
                          const char *private_key_file,
                          const char *ca_file,
                          valid_cns_t *valid_cn_list,
                          valid_snis_t *valid_sni_list
) {
  coap_endpoint_t *endpoint;
  coap_address_t listen_addr;
  coap_dtls_pki_t dtls_pki;
  coap_context_t *context;

  /* See coap_tls_library(3) */
  if (!coap_dtls_is_supported())
    return NULL;

  context = coap_new_context(NULL);
  if (!context)
    return NULL;

  memset (&amp;dtls_pki, 0, sizeof (dtls_pki));

  /* see coap_encryption(3) */
  dtls_pki.version                 = COAP_DTLS_PKI_SETUP_VERSION;
  dtls_pki.verify_peer_cert        = 1;
  dtls_pki.require_peer_cert       = 1;
  dtls_pki.allow_self_signed       = 1;
  dtls_pki.allow_expired_certs     = 1;
  dtls_pki.cert_chain_validation   = 1;
  dtls_pki.cert_chain_verify_depth = 1;
  dtls_pki.check_cert_revocation   = 1;
  dtls_pki.allow_no_crl            = 1;
  dtls_pki.allow_expired_crl       = 1;
  dtls_pki.validate_cn_call_back   = verify_cn_callback;
  dtls_pki.cn_call_back_arg        = valid_cn_list;
  dtls_pki.validate_sni_call_back  = verify_sni_callback;
  dtls_pki.sni_call_back_arg       = valid_sni_list;
  dtls_pki.additional_tls_setup_call_back = NULL;
  dtls_pki.client_sni              = NULL;
  dtls_pki.pki_key.key_type        = COAP_PKI_KEY_PEM;
  dtls_pki.pki_key.key.pem.ca_file = ca_file;
  dtls_pki.pki_key.key.pem.public_cert = public_cert_file;
  dtls_pki.pki_key.key.pem.private_key = private_key_file;

  if (coap_context_set_pki(context, &amp;dtls_pki)) {
    coap_free_context(context);
    return NULL;
  }

  coap_address_init(&amp;listen_addr);
  listen_addr.addr.sa.sa_family = AF_INET;
  listen_addr.addr.sin.sin_port = htons (5684);

  endpoint = coap_new_endpoint(context, &amp;listen_addr, COAP_PROTO_DTLS);
  if (!endpoint) {
    coap_free_context(context);
    return NULL;
  }

  /* See coap_resource(3) */
  init_resources(context);

  return context;
}</pre><p><span class="strong"><strong>CoAP Server DTLS PSK Setup</strong></span></p><pre class="programlisting">#include &lt;coap2/coap.h&gt;

static coap_context_t *
setup_server_context_psk (const char *hint,
                          const uint8_t *key,
                          unsigned key_len
) {
  coap_endpoint_t *endpoint;
  coap_address_t listen_addr;
  coap_context_t *context;

  /* See coap_tls_library(3) */
  if (!coap_dtls_is_supported())
    return NULL;

  context = coap_new_context(NULL);
  if (!context)
    return NULL;

  if (coap_context_set_psk(context, hint, key, key_len)) {
    coap_free_context(context);
    return NULL;
  }

  coap_address_init(&amp;listen_addr);
  listen_addr.addr.sa.sa_family = AF_INET;
  listen_addr.addr.sin.sin_port = htons (5684);

  endpoint = coap_new_endpoint(context, &amp;listen_addr, COAP_PROTO_DTLS);
  if (!endpoint) {
    coap_free_context(context);
    return NULL;
  }

  /* See coap_resource(3) */
  init_resources(context);

  return context;
}</pre></div><div class="refsect1"><a id="_see_also"></a><h2>SEE ALSO</h2><p><a href="man_coap_encryption.html" target="_self"><span class="strong"><strong>coap_encryption</strong></span>(3)</a>, <a href="man_coap_resource.html" target="_self"><span class="strong"><strong>coap_resource</strong></span>(3)</a>, <a href="man_coap_session.html" target="_self"><span class="strong"><strong>coap_session</strong></span>(3)</a> and <a href="man_coap_tls_library.html" target="_self"><span class="strong"><strong>coap_tls_library</strong></span>(3)</a></p></div><div class="refsect1"><a id="_further_information"></a><h2>FURTHER INFORMATION</h2><p>See "RFC7252: The Constrained Application Protocol (CoAP)" for further
information.</p></div><div class="refsect1"><a id="_bugs"></a><h2>BUGS</h2><p>Please report bugs on the mailing list for libcoap:
<a class="ulink" href="mailto:libcoap-developers@lists.sourceforge.net" target="_top">libcoap-developers@lists.sourceforge.net</a></p></div><div class="refsect1"><a id="_authors"></a><h2>AUTHORS</h2><p>The libcoap project &lt;<a class="ulink" href="mailto:libcoap-developers@lists.sourceforge.net" target="_top">libcoap-developers@lists.sourceforge.net</a>&gt;</p></div></div></body></html> coap_context(3)</p>
</div></div><!-- contents -->
</div><!-- PageDoc -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated on Fri Dec 27 2024 09:57:44 for libcoap by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.8 </li>
  </ul>
</div>
</body>
</html>
